之前发的实例只能进行图片检测,现在发一个能够实时检测视频和摄像头的注意:先打开摄像头,再点打开检测,CPU配置比较卡,GPU要快很多,如果要识别其他物体,需替换自己的训练数据集yolov3.weights 还有CFG文件 仅大家交流,我也是好久才搞会视频和摄像头检测!由于包括训练数据集,文件有点大约800M,上传不易,所以分高点,望理解! private void m_LoadImage_Btn_Click(object sender, EventArgs e)
{
try
{
var filename = OpenImagefileDlg();
if (filename != null && filename != "")
{
Mat img = Cv2.ImRead(filename);
//Imgwindow.Showimg(img);
rawimg = img.Clone();
if (isObjectDetect)
{
var blob = CvDnn.BlobFromImage(rawimg, 1.0 / 255, new OpenCvSharp.Size(416, 416), new Scalar(), true, false);
//load model and config, if you got error: "separator_index < line.size()", check your cfg file, must be something wrong.
var net = CvDnn.ReadNetFromDarknet(cfg, model);
#region set preferable
net.SetPreferableBackend(Backend.OPENCV);
/*
0:DNN_BACKEND_DEFAULT
1:DNN_BACKEND_HALIDE
2:DNN_BACKEND_INFERENCE_ENGINE
3:DNN_BACKEND_OPENCV
*/
net.SetPreferableTarget(Target.CPU);
/*
0:DNN_TARGET_CPU
1:DNN_TARGET_OPENCL
2:DNN_TARGET_OPENCL_FP16
3:DNN_TARGET_MYRIAD
4:DNN_TARGET_FPGA
*/
#endregion
//input data
net.SetInput(blob);
//get output layer name
var outNames = net.GetUnconnectedOutLayersNames();
//create mats for output layer
var outs = outNames.Select(_ => new Mat()).ToArray();
#region forward model
Stopwatch sw = new Stopwatch();
sw.Start();
net.Forward(outs, outNames);
sw.Stop();
Console.WriteLine($"Runtime:{sw.ElapsedMilliseconds} ms");
#endregion
//get result from all output
GetResult(outs, rawimg, threshold, nmsThreshold);
}
showImage(rawimg);
//Imgwindow.Showimg(rawimg);
img.Dispose();
}
}
catch (Exception ex)
{
throw (ex);
评论